'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth/context';
import { getMemoryStats } from '@/lib/api/memory';

interface AnalyticsPanelProps {
  className?: string;
}

export function AnalyticsPanel({ className = "" }: AnalyticsPanelProps) {
  const { user } = useAuth();
  const [stats, setStats] = useState<{
    memory: any;
    session: any;
    message: any;
  } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (user) {
      fetchStats();
    }
  }, [user]);

  const fetchStats = async () => {
    if (!user) return;
    
    setLoading(true);
    try {
      const memoryStats = await getMemoryStats();
      setStats({
        memory: memoryStats,
        session: null,
        message: null,
      });
    } catch (error) {
      console.error('Failed to get statistics:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className={`bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6 ${className}`}>
        <div className="flex items-center justify-center">
          <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
        </div>
      </div>
    );
  }

  return (
    <div className={`bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 ${className}`}>
      <div className="p-6 border-b border-gray-200 dark:border-gray-700">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Data Analytics</h3>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">Your usage statistics and insights</p>
      </div>

      <div className="p-6 space-y-6">
        {/* Memory statistics */}
        {stats?.memory && (
          <div>
            <h4 className="text-md font-medium text-gray-900 dark:text-white mb-3">Memory Statistics</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                  {stats.memory.total || 0}
                </div>
                <div className="text-sm text-blue-800 dark:text-blue-300">Total Memories</div>
              </div>
              <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-lg">
                <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                  {stats.memory.recentCount || 0}
                </div>
                <div className="text-sm text-green-800 dark:text-green-300">Last 7 Days</div>
              </div>
            </div>
            
            {stats.memory.byType && (
              <div className="mt-4">
                <h5 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Distribution by Type</h5>
                <div className="space-y-2">
                  {Object.entries(stats.memory.byType).map(([type, count]) => (
                    <div key={type} className="flex items-center justify-between">
                      <span className="text-sm text-gray-600 dark:text-gray-400 capitalize">{type}</span>
                      <span className="text-sm font-medium text-gray-900 dark:text-white">{count as number}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Session statistics */}
        {stats?.session && (
          <div>
            <h4 className="text-md font-medium text-gray-900 mb-3">Session Statistics</h4>
            <div className="grid grid-cols-3 gap-4">
              <div className="p-4 bg-purple-50 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">
                  {stats.session.totalSessions || 0}
                </div>
                <div className="text-sm text-purple-800">Total Sessions</div>
              </div>
              <div className="p-4 bg-orange-50 rounded-lg">
                <div className="text-2xl font-bold text-orange-600">
                  {stats.session.activeSessions || 0}
                </div>
                <div className="text-sm text-orange-800">Active Sessions</div>
              </div>
              <div className="p-4 bg-indigo-50 rounded-lg">
                <div className="text-2xl font-bold text-indigo-600">
                  {stats.session.averageDuration || 0} minutes
                </div>
                <div className="text-sm text-indigo-800">Average Duration</div>
              </div>
            </div>
          </div>
        )}

        {/* Message statistics */}
        {stats?.message && (
          <div>
            <h4 className="text-md font-medium text-gray-900 mb-3">Message Statistics</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-emerald-50 rounded-lg">
                <div className="text-2xl font-bold text-emerald-600">
                  {stats.message.totalMessages || 0}
                </div>
                <div className="text-sm text-emerald-800">Total Messages</div>
              </div>
              <div className="p-4 bg-pink-50 rounded-lg">
                <div className="text-2xl font-bold text-pink-600">
                  {stats.message.averagePerSession || 0}
                </div>
                <div className="text-sm text-pink-800">Average per Session</div>
              </div>
            </div>
          </div>
        )}

        {/* Usage trends */}
        <div>
          <h4 className="text-md font-medium text-gray-900 dark:text-white mb-3">Usage Trends</h4>
          <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <div className="text-center text-gray-500 dark:text-gray-400 text-sm">
              Usage trend chart feature under development...
            </div>
          </div>
        </div>

        {/* Achievement display */}
        <div>
          <h4 className="text-md font-medium text-gray-900 dark:text-white mb-3">Achievements</h4>
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 bg-yellow-500 rounded-full flex items-center justify-center">
                  <span className="text-white text-xs">🏆</span>
                </div>
                <div>
                  <div className="text-sm font-medium text-yellow-800 dark:text-yellow-300">Chat Novice</div>
                  <div className="text-xs text-yellow-600 dark:text-yellow-400">Complete 10 conversations</div>
                </div>
              </div>
            </div>
            
            <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 bg-gray-400 rounded-full flex items-center justify-center">
                  <span className="text-white text-xs">🔒</span>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600 dark:text-gray-400">Memory Master</div>
                  <div className="text-xs text-gray-500 dark:text-gray-500">Create 50 memories</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
